package com.keli.dt.analyzer;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.keli.common.DateFormatter;
import com.keli.dt.algorithm.LaneReportAlgo;
import com.keli.dt.model.LaneReport;
import com.keli.dt.model.TravelReport;

public class LaneReportHelper {
	private String detectClass;
	private String detectID;
	private String roadId;
	private String laneId;
	private String vehicleClass;
	
	String maxPassTime;
	private double speedSum;
	private List<TravelReport> travelReports;

	public String getDetectID() {
		return detectID;
	}

	public void setDetectID(String detectID) {
		this.detectID = detectID;
	}

	public String getRoadId() {
		return roadId;
	}

	public void setRoadId(String roadId) {
		this.roadId = roadId;
	}

	public String getLaneId() {
		return laneId;
	}

	public void setLaneId(String laneId) {
		this.laneId = laneId;
	}

	public String getVehicleClass() {
		return vehicleClass;
	}

	public void setVehicleClass(String vehicleClass) {
		this.vehicleClass = vehicleClass;
	}

	/**
	 * 默认构造方法
	 */
	private LaneReportHelper() {
		speedSum = 0;
		travelReports = new ArrayList<TravelReport>();
	}

	/**
	 * 带参构造方法
	 * @param tr 过车记录信息对象
	 */
	public LaneReportHelper(TravelReport tr) {
		this();
		this.detectClass = tr.getSBLX();
		this.detectID = tr.getSBBH();
		this.roadId = tr.getSECTIONID();	// 不使用tr.getDDBH();
		this.laneId = tr.getCDBH();
		this.vehicleClass = tr.getHPZL();	// 不使用tr.getCLLX();
		addTravelReport(tr);
	}
	
	/**
	 * 添加过车记录信息
	 * @param tr 过车记录信息
	 */
	public void addTravelReport(TravelReport tr) {
		speedSum = Double.parseDouble(tr.getCLSD());
		travelReports.add(tr);
		setMaxPassTime(tr.getGCSJ());
	}
	
	/**
	 * 设置最大过车时间
	 * @param date 过车时间
	 */
	private void setMaxPassTime(String date) {
		if (maxPassTime == null) {
			maxPassTime = date;
		} else {
			if (DateFormatter.max(date, maxPassTime)) {
				maxPassTime = date;
			}
		}
	}
	
	/**
	 * 计算车道平均速度
	 * @param volume
	 * @return
	 */
	public double getAverageSpeed(int volume) {
		return speedSum / volume;
	}
	
	/**
	 * 统计流量
	 * @return
	 */
	public int getVolume() {
		return travelReports.size();
	}

	/**
	 * 计算平均车流密度
	 * @return
	 */
	public String getAverageDensity() {
		int volume = getVolume();
		double speedAvg = getAverageSpeed(volume);
		return LaneReportAlgo.calculateDensity(volume, speedAvg);
	}
	
	public LaneReport toLaneReport() {
		LaneReport lr = new LaneReport();
		lr.setDETECT_CLASS(detectClass);
		lr.setDETECT_ID(detectID);
		lr.setROAD_ID(new BigDecimal(roadId));
		lr.setLANE(laneId);
		lr.setVEHICLE_CLASS(vehicleClass);
		int volume = getVolume();
		lr.setVOLUME(new BigDecimal(volume));
		lr.setSPEED(new BigDecimal(getAverageSpeed(volume)));
		lr.setDENSITY(getAverageDensity());
		lr.setCOLLEC_TIME(maxPassTime);
		lr.setCOLLEC_DATETIME(maxPassTime);
		return lr;
	}
}
